package com.jjz.id.common.password;

import com.jjz.id.common.cipher.RsaCipher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author ZJL
 * @create 2025-05-28-13:16
 */

public class RsaPasswordEncoder implements PasswordEncoder {
    private static final Logger log = LoggerFactory.getLogger(RsaPasswordEncoder.class);
    private final RsaCipher rsaCipher;

    public RsaPasswordEncoder(RsaCipher rsaCipher) {
        this.rsaCipher = rsaCipher;
    }

    public String encode(CharSequence rawPassword) {
        if (rawPassword == null) {
            throw new IllegalArgumentException("rawPassword cannot be null");
        } else {
            return this.rsaCipher.encrypt(rawPassword.toString());
        }
    }

    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if (rawPassword == null) {
            throw new IllegalArgumentException("rawPassword cannot be null");
        } else if (encodedPassword != null && encodedPassword.length() != 0) {
            return rawPassword.equals(this.rsaCipher.decrypt(encodedPassword));
        } else {
            log.warn("Empty encoded password");
            return false;
        }
    }
}
